package com.madixin.chat.service.impl;

import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import com.madixin.chat.constants.Constants;
import com.madixin.chat.dto.ChatMessageRequest;
import com.madixin.chat.dto.ChatMessageResponse;
import com.madixin.chat.exception.ChatBaseException;
import com.madixin.chat.model.ChatMessage;
import jakarta.annotation.PostConstruct;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;


@Service
public class ChatService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ChatService.class);

    @Autowired
    DashScopeChatModel chatModel;

    private ChatClient chatClient;

    @Autowired
    private ChatMessageService chatMessageService;

    @PostConstruct
    public void initChatClient() {
        this.chatClient = ChatClient.create(chatModel);
    }

    // @Override
    public Flux<String> mockProcessMessage(String token, ChatMessageRequest request) throws IOException {
        // 处理图片（如果有）
        if ("image".equals(request.getType()) && request.getImage() != null) {
            processImage(request.getImage());
        }

        // 模拟流式响应
        return Flux.just(
                        createSseEvent("thinking", "{\"content\": \"检测到\"}"),
                        createSseEvent("thinking", "{\"content\": \"问题\"}"),
                        createSseEvent("thinking", "{\"content\": \"涉及\"}"),
                        createSseEvent("thinking", "{\"content\": \"人工\"}"),
                        createSseEvent("thinking", "{\"content\": \"智能\"}"),
                        createSseEvent("thinking", "{\"content\": \"发展\"}"),
                        createSseEvent("thinking", "{\"content\": \"准备回答...\"}"),
                        createSseEvent("thinking", "{\"content\": \"收集最新的AI发展信息...\"}"),
                        createSseEvent("content", "{\"content\": \"当然可以！最近人工智能领域有几个重要的发展：\"}"),
                        createSseEvent("content", "{\"content\": \"\\n\\n1. 多模态大型语言模型的进步，如GPT-4V、Claude 3和Gemini，它们能够同时处理文本和图像输入。\"}"),
                        createSseEvent("content", "{\"content\": \"\\n\\n2. 生成式AI工具的普及，特别是在图像、音频和视频生成方面。\"}"),
                        createSseEvent("content", "{\"content\": \"\\n\\n3. AI辅助编程工具的发展，如GitHub Copilot和Amazon CodeWhisperer，提高了开发效率。\"}"),
                        createSseEvent("content", "{\"content\": \"\\n\\n4. 边缘AI技术的进步，使AI能够在低功耗设备上本地运行。\"}"),
                        createSseEvent("content", "{\"content\": \"\\n\\n你对哪个方面特别感兴趣？我可以提供更详细的信息。\"}"),
                        createSseEvent("done", "ok")
                ).delayElements(Duration.ofMillis(500));// 每500ms发送一个事件
    }

    public Flux<ChatMessageResponse> processRealMessage(ChatMessageRequest request) throws ChatBaseException {
        // 处理图片（如果有）
        if ("image".equals(request.getType()) && request.getImage() != null) {
            processImage(request.getImage());
        }

        // 获取会话的历史消息
        List<Message> messages = new ArrayList<>();
        List<ChatMessage> chatMessages = this.chatMessageService.getConversationMessage(request.getSessionId(), 1, 20);
        for (ChatMessage chatMessage : chatMessages) {
            if (Constants.MESSAGE_ROLE_USER.equals(chatMessage.getRole())) {
                messages.add(new UserMessage(chatMessage.getContent()));
            } else {
                messages.add(new AssistantMessage(chatMessage.getContent()));
            }
        }

        // 记录用户的输入
        ChatMessage message = new ChatMessage();
        message.setContent(request.getContent());
        message.setType("text");
        message.setRole(Constants.MESSAGE_ROLE_USER);
        chatMessageService.insertMessage(request.getSessionId(), message);

        StringBuilder sb = new StringBuilder();
        // 模拟流式响应
        return this.chatClient.prompt().messages(messages).user(request.getContent()).stream().chatResponse().doOnNext(response -> {
                    String content = response.getResult().getOutput().getText();
                    if (StringUtils.isNotBlank(content)) {
                        // 记录完整的响应对象
                        sb.append(content);
                    }
                })
                // 在流结束时记录完整的会话内容
                .doOnComplete(() -> {
                    // 这里记录消息到数据库
                    String content = sb.toString();
                    LOGGER.info("收到模型原始响应结束: " + content);
                    ChatMessage assistantMessage = new ChatMessage();
                    assistantMessage.setContent(content);
                    assistantMessage.setType("text");
                    assistantMessage.setRole(Constants.MESSAGE_ROLE_ASSISTENT);
                    try {
                        chatMessageService.insertMessage(request.getSessionId(), assistantMessage);
                    } catch (ChatBaseException e) {
                        LOGGER.error("processMessage2 doOnComplete insertMessage error");
                    }
                }).map(response -> {
                    String content = response.getResult().getOutput().getText();
                    String thinking = response.getResults().get(0).getOutput().getMetadata().get("reasoningContent").toString();
                    if (StringUtils.isNotEmpty(content)) {
                        LOGGER.info("content" + content);
                        return new ChatMessageResponse("content", content);
                    } else if (StringUtils.isNotEmpty(thinking)) {
                        LOGGER.info("thinking" + thinking);
                        return new ChatMessageResponse("thinking", thinking);
                    } else {
                        LOGGER.info("done~~~~");
                        return new ChatMessageResponse("done", "");
                    }
                });
    }

    private void processImage(MultipartFile image) {
        // 处理图片逻辑，如存储到文件系统或云存储
        // 这里仅打印图片信息
        System.out.println("Processing image: " + image.getOriginalFilename());
    }

    private String createSseEvent(String event, String data) {
        return "event: " + event + "\n" + "data: " + data + "\n\n";
    }
}
